/**
 *		Licensed to the Apache Software Foundation (ASF) under one
 *     or more contributor license agreements.  See the NOTICE file
 *     distributed with this work for additional information
 *     regarding copyright ownership.  The ASF licenses this file
 *     to you under the Apache License, Version 2.0 (the
 *     "License"); you may not use this file except in compliance
 *     with the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing,
 *     software distributed under the License is distributed on an
 *     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *     KIND, either express or implied.  See the License for the
 *     specific language governing permissions and limitations
 *     under the License.
 *     
 *     Image Resizer Project
 */

package image.resizer;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Resize engine configuration object.
 * @author DUDAREV
 */
public class ResizerConfig {
	
	private static final String CLASS_NAME = ResizerConfig.class.getName();
	private static final Logger logger = Logger.getLogger(ResizerConfig.class.getPackage().getName());
	private static final Level FINER_LEVEL = Level.FINER;
	
	// Keys
	/** Root directory for sourse images file tree key */
	public static final String SOURCE_DIR_PATH_KEY = "resizer.source.path";
	/** Root directory for resulted images file tree key */
	public static final String TARGET_DIR_PATH_KEY = "resizer.target.path";
	/** Maximal image edge length in pixels key */
	public static final String MAX_IMAGE_SIZE_KEY = "resizer.max.image.size";
	/** Search subdirectories of source images directory key */
	public static final String SEARCH_SUB_DIRS_KEY = "resizer.search.subdirs.flag";
	/** Number of threads to be emloyeed key */
	public static final String NUM_OF_THREADS_KEY = "resizer.threads.number";
	// Defaults
	private static final String DEFAULT_SOURCE_DIR = System.getProperty("user.dir");
	private static final String DEFAULT_DESTINATION_DIR = System.getProperty("user.home"); // TODO check overriding policy
	private static final boolean DEFAULT_SEARCH_SUB_DIRS = false;
	private static final int DEFAULT_THREADS_NUM = 1;
	private static final int DEFAULT_MAX_IMAGE_SIZE = 1500;
	
	private String sourceDirPath;
	private String targetDirPath;
	private int maxImageSize;
//	private String[] extentions; TODO
	private boolean searchSubDirs;
	private int numberOfThreads;
	
	public ResizerConfig() {
		sourceDirPath = DEFAULT_SOURCE_DIR;
		targetDirPath = DEFAULT_DESTINATION_DIR;
		maxImageSize = DEFAULT_MAX_IMAGE_SIZE;
		searchSubDirs = DEFAULT_SEARCH_SUB_DIRS;
		numberOfThreads = DEFAULT_THREADS_NUM;
	}
	
	public String getSourceDirPath() {
		return sourceDirPath;
	}
	public void setSourceDirPath(String sourceDirPath) {
		this.sourceDirPath = sourceDirPath;
	}
	public String getTargetDirPath() {
		return targetDirPath;
	}
	public void setTargetDirPath(String targetDirPath) {
		this.targetDirPath = targetDirPath;
	}
	public int getMaxImageSize() {
		return maxImageSize;
	}
	public void setMaxImageSize(int maxImageSize) {
		this.maxImageSize = maxImageSize;
	}
	public boolean isSearchSubDirs() {
		return searchSubDirs;
	}
	public void setSearchSubDirs(boolean searchSubDirs) {
		this.searchSubDirs = searchSubDirs;
	}
	public int getNumOfThreads() {
		return numberOfThreads;
	}
	public void setNumOfThreads(int numberOfThreas) {
		this.numberOfThreads = numberOfThreas;
	}

	/**
	 * Loads configuration from properties object
	 * @param properties
	 */
	public void loadFromProperties(Properties properties)
	{
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.entering(CLASS_NAME, "loadFromProperties", properties);
		}
		sourceDirPath = getProperyValue(properties, SOURCE_DIR_PATH_KEY, DEFAULT_SOURCE_DIR); 
		targetDirPath = getProperyValue(properties, TARGET_DIR_PATH_KEY, DEFAULT_DESTINATION_DIR);
		String maxSize = properties.getProperty(MAX_IMAGE_SIZE_KEY);
		if(!Utils.isEmpty(maxSize))
		{
			try
			{
				maxImageSize = Integer.parseInt(maxSize);
			}
			catch(NumberFormatException nfe)
			{
				RuntimeException rte = new RuntimeException("Failed to parse maximal image size property ("+maxSize+") for key: "+ MAX_IMAGE_SIZE_KEY);
				logger.throwing(CLASS_NAME, "loadFromProperties", rte);
				throw rte;
			}
		}
		else
		{
			maxImageSize = DEFAULT_MAX_IMAGE_SIZE;
		}
		
		String numOfThreadsStr = properties.getProperty(NUM_OF_THREADS_KEY);
		if(!Utils.isEmpty(numOfThreadsStr))
		{
			try
			{
				numberOfThreads = Integer.parseInt(numOfThreadsStr);
			}
			catch(NumberFormatException nfe)
			{
				RuntimeException rte = new RuntimeException("Failed to parse number of threads property ("+numberOfThreads+") for key: "+ NUM_OF_THREADS_KEY);
				logger.throwing(CLASS_NAME, "loadFromProperties", rte);
				throw rte;
			}
		}
		else
		{
			numberOfThreads = DEFAULT_THREADS_NUM;
		}
		String searchSubDirsStr = properties.getProperty(SEARCH_SUB_DIRS_KEY);
		if(!Utils.isEmpty(searchSubDirsStr))
		{
			 searchSubDirs = searchSubDirsStr.equalsIgnoreCase("true");
			 if(!searchSubDirs && !searchSubDirsStr.equalsIgnoreCase("false"))
			 {
				RuntimeException rte = new RuntimeException("Failed to parse search sub directories property ("+searchSubDirsStr+") for key: "+ SEARCH_SUB_DIRS_KEY);
				logger.throwing(CLASS_NAME, "loadFromProperties", rte);
				throw rte;
			 }
		}
		else
		{
			searchSubDirs = DEFAULT_SEARCH_SUB_DIRS;
		}
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.exiting(CLASS_NAME, "loadFromProperties");
		}
	}
	
	/**
	 * Stores configuration into supplied properties object. 
	 */
	public void storeToProperties(Properties properties)
	{
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.entering(CLASS_NAME, "loadFromProperties", properties);
		}
		if(properties == null)
		{
			RuntimeException rte = new RuntimeException("Empty properties supplied for saving.");
			logger.throwing(CLASS_NAME, "loadFromProperties", rte);
			throw rte;
		}
		properties.put(SOURCE_DIR_PATH_KEY, sourceDirPath);
		properties.put(TARGET_DIR_PATH_KEY, targetDirPath);		
		properties.put(MAX_IMAGE_SIZE_KEY, String.valueOf(maxImageSize));
		properties.put(SEARCH_SUB_DIRS_KEY, String.valueOf(searchSubDirs));
		properties.put(NUM_OF_THREADS_KEY, String.valueOf(numberOfThreads));
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.exiting(CLASS_NAME, "loadFromProperties");
		}
	}
	
	@Override
	public Object clone() {
		ResizerConfig clone = new ResizerConfig();
		clone.maxImageSize = maxImageSize;
		clone.searchSubDirs = searchSubDirs;
		clone.sourceDirPath = sourceDirPath;
		clone.targetDirPath = targetDirPath;
		clone.numberOfThreads = numberOfThreads;
		return clone;
	}
	
	private static String getProperyValue(Properties props, String key, String defaultVal)
	{
		String value = props.getProperty(key);
		if(Utils.isEmpty(value))
		{
			value = defaultVal;
		}
		return value;
	}
}
